<?php

namespace app\admin\controller;

use app\common\model\GoodsModel;
use app\common\model\OrderReceiptModel;
use app\common\model\StorageLogModel;
use app\common\model\StorageManageModel;
use app\common\model\StorageModel;
use cmf\controller\AdminBaseController;
use cmf\lib\Storage;
use think\Db;
use think\db\Query;
use think\Request;

class CloudController extends AdminBaseController
{

    private function curlPost($api, $postdata)
    {
        $url = "http://yuncangapi.maer.pro" . $api;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT,300);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    public function index()
    {
        $reg = Db::name('cloud_user')->where('id', 1)->find();
        $info = $service = [];
        $logstate = 0;
        if ($reg) {
            if ($reg['logstate'] == 1) $logstate = 1;
            $info['username'] = $reg['username'];
            $ret = $this->getmoney($reg);
            if ($ret['code'] == 1) {
                $info['money'] = $ret['data'];
                Db::name('cloud_user')->where('id', 1)->update(['balance' => $ret['data']]);
            } else {
                $info['money'] = '0.00';
            }
            $ret = $this->loadService(['op' => 1, 'token' => $reg['token']]);
            if ($ret['code'] == 1) {
                $service = $ret['data'];
            }
        }

        $this->assign('reg', $reg);
        $this->assign('logstate', $logstate);
        $this->assign('info', $info);
        $this->assign('service', $service);
        return $this->fetch();
    }

    public function sms()
    {
        $op = $this->request->post('op');
        if (!in_array($op, ['get', 'check'])) $op = 'get';
        $mobile = $this->request->post('mobile');
        $event = $this->request->post('event', 'register');
        if(!preg_match('/^1[3456789]\d{9}$/', $mobile)) $this->error('手机号格式错误');
        $args = array('mobile' => $mobile, 'event' => $event);
        if ($op === 'get') {
            $api = '/service/sms/send';
        } else {
            $api = '/service/sms/check';
            $captcha = $this->request->post('code');
            $args['captcha'] = $captcha;
        }
        $ret = $this->curlPost($api, $args);
        $ret = json_decode($ret, true);
        return $ret;
    }

    public function reg()
    {
        if ($this->request->isPost()) {
            $param = $this->request->only(['mobile', 'password', 'code', 'wx', 'qq', 'code', 'service']);
            $data = Db::name('option')->where('option_name', 'site_info')->find();
            $option = json_decode($data['option_value'], true);
            $param['reason'] = $option['site_name'];

            $api = '/service/user/register';
            $args = $param;
            $ret = $this->curlPost($api, $args);
            $ret = json_decode($ret, true);
            cache('pass', $param['password']);
            if ($ret['code'] === 1) {
                cache('userInfo', $ret['data']['userinfo']);
                cache('salt', $ret['data']['userinfo']['salt']);
                $insertId = Db::name('cloud_user')->insertGetId([
                    'username' => $param['mobile'],
                    'password' => md5(md5($param['password']).$ret['data']['userinfo']['salt'])
                ]);
                $result = $this->connect();
                if ($result['code'] == 1) {
                    cache('apiToken', $result['data']['token']);
                    Db::name("cloud_user")->where('id', $insertId)->update(['token' => $result['data']['token'], 'uid' => $ret['data']['userinfo']['id']]);
                    $this->success($ret['msg'], url('cloud/index'));
                } else {
                    $this->error('注册成功：'. $result['msg'], url('cloud/index'));
                }
            } else {
                cache('userInfo', $ret['data']);
                $this->error($ret['msg']);
            }
        }
        $service = $this->loadService();
        if ($service['code'] == 1) {
            $service = $service['data'];
        } else {
            $service = ['list' => [], 'rec' => []];
        }
        $this->assign('service', $service);
        return $this->fetch();
    }

    public function loadService($args = [])
    {
        $api = '/service/user/loadService';
        $ret = json_decode($this->curlPost($api, $args), true);

        if ($this->request->isAjax()) {
            return json(['code' => $ret['code'], 'msg' => $ret['msg'], 'data' => $ret['data']]);
        }
        return $ret;
    }

    private function connect()
    {
        $api = '/service/user/connect_test';
        $userInfo = Db::name('cloud_user')->where('id', 1)->where('logstate', 1)->find();
        $args = array(
            'id' => cache('userInfo')['id'],
            'key' => md5($userInfo['username'].$userInfo['password'].cache('salt'))
        );
        $ret = $this->curlPost($api, $args);
        $ret = json_decode($ret, true);
        return $ret;
    }

    private function getmoney($userInfo)
    {
        $api = '/service/user/get_money';
        $args = array(
            'id' => $userInfo['uid'],
            'token' => $userInfo['token']
        );
        $ret = $this->curlPost($api, $args);
        $ret = json_decode($ret, true);
        return $ret;
    }

    public function recharge()
    {
        if ($this->request->isPost()) {
            $payType = $this->request->post('payType', 'alipay');
            $amount = $this->request->post('amount', '100');

            $userInfo = Db::name('cloud_user')->where('id', 1)->where('logstate', 1)->find();
            $api = '/api/api/pay';
            $args = array(
                'token' => $userInfo['token'],
                'amount' => $amount,
                'payType' => $payType
            );
            $ret = $this->curlPost($api, $args);
            $ret = json_decode($ret, true);
            if ($ret['code'] == 200) {
                $this->success($ret['msg'], '', $ret['data']);
            } else {
                $this->error($ret['msg']);
            }
        }
        $userInfo = Db::name('cloud_user')->where('id', 1)->where('logstate', 1)->find();
        $priceList = array('50' => 50, '100' => 100, '500' => 500, '2000' => 2000);
        $payType = array('alipay' => '支付宝', 'wechat' => '微信');
        $this->assign('priceList', $priceList);
        $this->assign('payType', $payType);
        $this->assign('userInfo', $userInfo);
        return $this->fetch();
    }

    public function state()
    {
        if ($this->request->isPost()) {
            $oid = $this->request->post('oid');
            $userInfo = Db::name('cloud_user')->where('id', 1)->where('logstate', 1)->find();
            $api = '/service/user/rechargeState';
            $args = array(
                'token' => $userInfo['token'],
                'oid' => $oid
            );
            $ret = json_decode($this->curlPost($api, $args), true);
            if ($ret['code'] == 1) {
                $result = $this->getmoney($userInfo);
                if ($result['code'] == 1) {
                    Db::name('cloud_user')->where('id', 1)->update(['balance' => $result['data']]);
                }
                $this->success($ret['msg'], $ret['data']);
            } else {
                $this->error($ret['msg']);
            }
        }
    }

    public function uppwd()
    {
        if ($this->request->isPost()) {
            $mobile = $this->request->post('mobile');
            $captcha = $this->request->post('code');
            $pass = $this->request->post('pass');
            $api = '/service/user/resetpwd';
            $userInfo = Db::name('cloud_user')->where('id', 1)->where('logstate', 1)->find();
            $args = array(
                'token' => $userInfo['token'],
                'mobile' => $mobile,
                'captcha' => $captcha,
                'pass' => $pass
            );
            $ret = json_decode($this->curlPost($api, $args), true);
            if ($ret['code'] == 1) {
                Db::name('cloud_user')->where('id', 1)->update(['password' => $ret['data']['p']]);
                cache('salt', $ret['data']['s']);
                $this->success($ret['msg']);
            } else {
                $this->error($ret['msg']);
            }
        }
    }

    public function logout()
    {
        Db::name('cloud_user')->where('id', 1)->update(['logstate' => 0]);
        cache('apiToken', NULL);
        cache('userInfo', NULL);
        $this->success('退出成功',url('cloud/index'));
    }

    public function login()
    {
        if ($this->request->isPost()) {
            $mobile = $this->request->post('mobile');
            $pass = $this->request->post('pass');

            $userInfo = Db::name('cloud_user')->where('id', 1)->find();
            if ($userInfo['username'] != $mobile) $this->error('手机号与注册手机号不一致');

            $api = '/service/user/login';
            $args = array(
                'account' => $mobile,
                'password' => $pass
            );
            $ret = json_decode($this->curlPost($api, $args), true);
            if ($ret['code'] == 1) {
                cache('userInfo', $ret['data']['userinfo']);
                cache('salt', $ret['data']['userinfo']['salt']);
                Db::name('cloud_user')->where('id', 1)->update(['logstate' => 1]);
                $result = $this->connect();
                if ($result['code'] == 1) {
                    cache('apiToken', $result['data']['token']);
                    Db::name('cloud_user')->where('id', 1)->update(['token' => $result['data']['token']]);
                }
                $this->success($ret['msg'], url('cloud/index'));
            } else {
                $this->error($ret['msg']);
            }
        }
    }

    public function sync()
    {
        $goodsapi = '/service/goods/get_all_goods';
        $storaapi = '/service/storage/get_all_storage';
        $userInfo = Db::name('cloud_user')->where('id', 1)->where('logstate', 1)->find();
        $args = array(
            'token' => $userInfo['token']
        );
        $goodsList = json_decode($this->curlPost($goodsapi, $args), true);
        $storaList = json_decode($this->curlPost($storaapi, $args), true);
        if ($goodsList['code'] == 1 && $storaList['code'] == 1) {
            $goodsList = $goodsList['data'];
            $storaList = $storaList['data'];
            // $ret = false;
            // Db::startTrans();
            try {
                foreach ($goodsList as $v) {
                    unset($v['goods_class_text']);
                    $exi = Db::name('cloud_goods')->where(['id' => $v['id'], 'goods_name' => $v['goods_name']])->find();
                    if ($exi) {
                        $ret = Db::name('cloud_goods')->where('id', $exi['id'])->update($v);
                    } else {
                        $v['online_switch'] = 0;
                        $ret = Db::name('cloud_goods')->insert($v);
                    }
                }
                foreach ($storaList as $v) {
                    unset($v['is_third_text']);
                    $exi = Db::name('cloud_storage')->where(['id' => $v['id'], 'name' => $v['name']])->find();
                    if ($exi) {
                        $ret = Db::name('cloud_storage')->where('id', $exi['id'])->update($v);
                    } else {
                        $ret = Db::name('cloud_storage')->insert($v);
                    }
                }
            } catch (\Exception $e) {
                // Db::rollback();
                $msg = $e->getMessage();
            }
            if (!isset($msg)) {
                // Db::commit();
                $this->success("同步成功");
            } else {
                // Db::rollback();
                $this->error('同步失败.');
            }
        } else {
            $this->error('同步失败');
        }
    }

    public function goodsindex()
    {
        $map = [];
        $keyword = $this->request->post('keyword', '', 'trim');
        if ($keyword) $map[] = ['goods_name', 'like', "%{$keyword}%"];
        $list = Db::name('cloud_goods')->where($map)->order('id desc')->paginate(10, false, ['query' => $this->request->param()]);
        $this->assign('list', $list);
        return $this->fetch();
    }

    public function goodstate($id, $status)
    {
        if (($id > -1) && ($status > -1)) {
            $goods = Db::name('cloud_goods')->where('id', $id)->find();
            $storaInfo = Db::name('cloud_storage')->where('id', $goods['storage_id'])->find();
            if (!$goods) $this->error('未查询到该商品');
            if (!$storaInfo) $this->error('未查询到该仓库');
            Db::name('cloud_goods')->where('id', $id)->update(['online_switch' => $status]);
            if ($status == 1) {
                $args = array(
                    'create_time' => time(),
                    'update_time' => time(),
                    'goods_images' => json_encode([$goods['goods_images']]),
                    'goods_price' => $goods['goods_price'],
                    'goods_name' => $goods['goods_name'],
                    'goods_num' => $goods['goods_inventory'],
                    'goods_sale_num' => $goods['goods_num'],
                    'goods_status' => 1,
                    'image' => $goods['goods_images'],
                    'is_index' => $goods['index_switch'],
                    'is_top' => $goods['top_switch'],
                    'is_new' => $goods['new_switch'],
                    'weight' => $goods['goods_weight'],
                    'cloud_id' => $goods['id'],
                    'goods_verify' => 1,
                    'mid' => 5
                );
                $ret = GoodsModel::create($args);
                $stoArgs = array(
                    'store_name' => $storaInfo['name'],
                    'price' => $storaInfo['deliver_price'],
                    'send_address' => $storaInfo['city'].$storaInfo['detailed_address'],
                    'cloud_id' => $storaInfo['id'],
                    'mid' => 5
                );
                $stoExi = StorageModel::where('cloud_id', $storaInfo['id'])->find();
                if (!$stoExi) {
                    $stoRet = StorageModel::create($stoArgs);
                    $exi = StorageLogModel::where('sid', $storaInfo['id'])->where('goods_id', $id)->find();
                    if (!$exi) {
                        StorageLogModel::create([
                            'sid' => $stoRet->id,
                            'goods_id' => $ret->id,
                            'goods_num' => $goods['goods_inventory'],
                            'storage_name' => $goods['storage_name']
                        ]);
                    } else {
                        StorageLogModel::where('id', $exi['id'])->update(['goods_num' => $goods['goods_inventory']]);
                    }
                } else {
                    $exi = StorageLogModel::where('sid', $storaInfo['id'])->where('goods_id', $id)->find();
                    if (!$exi) {
                        StorageLogModel::create([
                            'sid' => $stoExi->id,
                            'goods_id' => $ret->id,
                            'goods_num' => $goods['goods_inventory'],
                            'storage_name' => $goods['storage_name']
                        ]);
                    } else {
                        StorageLogModel::where('id', $exi['id'])->update(['goods_num' => $goods['goods_inventory']]);
                    }
                }
            } else {
                $gid = GoodsModel::where('cloud_id', $id)->find();

                $stoExi = StorageModel::where('cloud_id', $storaInfo['id'])->find();
                // $ret = StorageModel::where('cloud_id', $storaInfo['id'])->delete();
                if ($stoExi) {
                    $ret = StorageLogModel::where('sid', $stoExi['id'])->where('goods_id', $gid['id'])->delete();
                }
                $ret = GoodsModel::where('cloud_id', $id)->delete();
            }
            if ($ret) {
                $this->success('操作成功');
            } else {
                $this->error('操作失败');
            }
        } else {
            $this->error('未知参数');
        }
    }

    public function batchSetGoodsPrice()
    {
        $ids = $this->request->post('ids');
        $price = $this->request->post('price');
        if (!$ids || !$price) $this->error('未知参数');
        $ret = Db::name('cloud_goods')->where('id', 'in', $ids)->setField('goods_price', $price);
        if ($ret) {
            $this->success('批量操作成功');
        } else {
            $this->error('批量操作失败');
        }
    }

    public function storaindex()
    {
        $map = [];
        $keyword = $this->request->param('keyword', '', 'trim');
        if ($keyword) $map[] = ['name', 'like', "%{$keyword}%"];
        $list = Db::name('cloud_storage')->where($map)->order('id desc')->paginate(10, false, ['query' => $this->request->param()]);
        $this->assign('list', $list);
        return $this->fetch();
    }

    public function batchSetStoraPrice()
    {
        $ids = $this->request->post('ids');
        $price = $this->request->post('price');
        if (!$ids || !$price) $this->error('未知参数');
        $ret = Db::name('cloud_storage')->where('id', 'in', $ids)->setField('deliver_price', $price);
        if ($ret) {
            $this->success('批量操作成功');
        } else {
            $this->error('批量操作失败');
        }
    }

    public function wechat()
    {
        $userInfo = Db::name('cloud_user')->where('id', 1)->where('logstate', 1)->find();
        $api = '/service/user/wechat';
        $args = array('token' => $userInfo['token']);
        $ret = json_decode($this->curlPost($api, $args), true);
        if ($ret['code'] == 1) {
            $this->success('客服微信', '', $ret['data']);
        } else {
            $this->error($ret['msg']);
        }
    }

    public function logs()
    {
        $page = $this->request->param('page/d', 1);
        $userInfo = Db::name('cloud_user')->where('id', 1)->where('logstate', 1)->find();
        $api = '/service/user/logs';
        $args = array('token' => $userInfo['token'], 'page' => $page);
        $ret = json_decode($this->curlPost($api, $args), true);
        if ($ret['code'] == 1) {
            $list = $ret['data'];//json_decode(json_encode($ret['data']));
            $this->assign('list', $list);
        } else {
            $this->error($ret['msg'], url('cloud/index'));
            $this->redirect('cloud/index');
        }
        return $this->fetch();
    }

    public function reloadWaybill()
    {
        $userInfo = Db::name('cloud_user')->where('id', 1)->where('logstate', 1)->find();

        $list = OrderReceiptModel::where(
            function (Query $query) {
                $query->field('self_order_no');
                $query->where('show_status', 1)->where('order_status', 0);
                $time = time() - 7200;
                $query->where('add_time', '<', $time);
                $query->whereNull('delivery_no');
            })->order('id desc')->paginate();

        $api = '/service/order/reLoadWaybill';
        $args = array(
            'token' => $userInfo['token'],
            'package_no' => $list
        );
        $ret = json_decode($this->curlPost($api, $args), true);
        if ($ret['code'] == 1) {
            $ret = $ret['data'];
            foreach ($ret as $item) {
                if ($item['order_status'] == 3) {
                    OrderReceiptModel::where('self_order_no', $item['package_no'])->update([
                        'delivery_time' => time(),
                        'delivery_no' => $item['waybill_code'],
                        'order_status' => 1,
                    ]);
                }
            }
            $this->success('运单号更新成功', url('order/index'));
        } else {
            $this->error($ret['msg'], url('order/index'));
        }
    }

}
